package com.wholeintech.ble;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.wholeintech.entity.Navigation;
import com.wholeintech.dao.NavigationDao;
import com.wholeintech.zigbee.gw.DeviceManager;
import com.wholeintech.utils.CommonUtil;
import com.wholeintech.entity.DeviceDb;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import static com.wholeintech.ble.DeviceList.*;
import static com.wholeintech.ble.Utils.logPrint;
import static com.wholeintech.utils.CommonIntent.*;


/**
 * 蓝牙服务
 */
public class BleService extends Service {

    private final static String TAG = "MyBleService";
    private final static boolean debug = true;

    private final static String ACTION_BLE_ADD = "com.wit.device.add";
    private final static String ACTION_BLE_DELETE = "com.wit.device.remove";
    private final static String ACTION_BLE_DOOR_STATE = "com.wit.door.magnets";
    //private final static String ACTION_BLE_GETSTATE = "com.wholeintech.lyle.BleServer.getstate";

    private static final int YEELIGHT_BRIGHTNESS = 1;
    private static final int YEELIGHT_COLOR_BRIGHTNESS = 2;
    private static final int YEELIGHT_CTL_MDELAY = 120;

    private static final int BLE_ADV_ID_ADDR = 5;
    private static final int BLE_ADV_DEV_ID_ADDR = 9;
    private static final int BLE_ADV_DATA_ADDR = 9 + 12;

    private static final int BLE_ADV_TEMP_DATA_ADDR = 9 + 12;
    private static final int BLE_ADV_HUMI_DATA_ADDR = BLE_ADV_TEMP_DATA_ADDR + 2;
    private static final int BLE_ADV_PM25_DATA_ADDR = BLE_ADV_HUMI_DATA_ADDR + 2;
    private static final int BLE_ADV_CO2_DATA_ADDR = BLE_ADV_PM25_DATA_ADDR + 2;
    private static final int BLE_ADV_MSG_DATA_ADDR = BLE_ADV_CO2_DATA_ADDR + 2;

    public static final int TRUE = 1;
    public static final int FALSE = 0;

    private final static String doorOpen = "0201041AFF590002150112233445566778899AABBCCDDEEFF0010200AAC30000000000000000000000000000000000000000000000000000000000000000";
    private final static String doorClose = "0201041AFF590002150112233445566778899AABBCCDDEEFF001020055C30000000000000000000000000000000000000000000000000000000000000000";

    private final static String shockOpen = "0201041AFF590002150112233445566778899AABBCCDDEEFF0010200FFC30000000000000000000000000000000000000000000000000000000000000000";
    private final static String shockClose = "0201041AFF590002150112233445566778899AABBCCDDEEFF0010200CCC30000000000000000000000000000000000000000000000000000000000000000";


    public static final int BLE_NETWORK = 2;
    public static final int ETHERNET_NETWORK = 3;
    public static final int WIFI_NETWORK = 4;

    private ArrayList<String> mListMacAndState;

    Vector<DevInfoItem> mDevInfoItem;

    private BluetoothManage mBleMan;

    public TopBoxDev mTopBox;
    public AirRadioDevice mAirRadio;

    private YeeLightDev mYeeLight;

    private Context mContext;

    private HandlerThread mHandlerAgainThread = new HandlerThread("AgainScan");

    public Handler mHandlerAgainScan;

    public BleService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mContext = this;

        mDevInfoItem = new Vector<DevInfoItem>();
        mListMacAndState = new ArrayList<String>();

        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ACTION_BLE_ADD);
        mFilter.addAction(ACTION_BLE_DELETE);
/*
        mFilter.addAction(ACTION_CTL_LIGHT);
        mFilter.addAction(ACTION_CTL_AIRCONDITION);
        mFilter.addAction(ACTION_CTL_PROJECTOR);
        mFilter.addAction(ACTION_CTL_AIRCLEANER);
        mFilter.addAction(ACTION_CTL_FRESHAIR);*/

        //从zigbee分类转发过来的广播
        mFilter.addAction(ACTION_DEV_CTL_BY_BLE);

        mFilter.addAction(ACTION_HCP_UPDATED);

        //mFilter.addAction(ACTION_BLE_GETSTATE);
        registerReceiver(mReceiver, mFilter);
        mHandlerAgainThread.start();
        mHandlerAgainScan = new Handler(mHandlerAgainThread.getLooper());

        mHandlerAgainScan.post(devCtlFbCheckRunnable);
        mBleMan = new BluetoothManage(this, mDevInfoItem) {
            @Override
            public void getTopBoxSensorData(String address, byte[] data) {
                mTopBox.setSensorData(address, data);
            }

            @Override
            public void getAirRadioSensorData(String address, byte[] data) {
                mAirRadio.setSensorData(address, data);
            }

            @Override
            public void checkDoorStateBackCall(final String mac, final String record) {
                {
                    String mymac = mac.replace(":", "");
                    //Log.e(TAG, mac + "|" + record);
                    byte[] advdata = CommonUtil.hex2byte(record);
                    if (advdata[BLE_ADV_ID_ADDR] == 0x43 && advdata[BLE_ADV_ID_ADDR + 1] == 0x48) {
                        updateMagDb(mymac, advdata);
                        int msg = (advdata[BLE_ADV_MSG_DATA_ADDR]) & 0xff;
                        // Log.e(TAG, mac + "|" +"msg :"+ msg);
                    }
                }


            }

            @Override
            public void findTopBoxAddrBackCall(final String address) {
                /*for (int i = 0; i < mDevInfoItem.size(); i++) {
                    if (address.equals(mDevInfoItem.get(i).getDevMAC())) {

                        Log.e(TAG, "Connect:" + address);
                        mBleMan.connect(address);

                        break;
                    }
                }*/

                bleDevsConnect(address);


            }
        };

        mBleMan.initialize();

        addToDevList();

        mTopBox = new TopBoxDev(this, mDevInfoItem);
        mAirRadio = new AirRadioDevice(this);
        mYeeLight = new YeeLightDev(this, mDevInfoItem);

        Log.e(TAG, "BLE Service start");

        //  mHnadlerRoomState.sendEmptyMessage(1);
    }

    int devresetcnt = 0;

    int getScanCnt = 0;

    Runnable devCtlFbCheckRunnable = new Runnable() {
        @Override
        public void run() {
            while (true) {
                BluetoothAdapter blueadapter = BluetoothAdapter.getDefaultAdapter();
                //Log.e(TAG, "devCtlFbCheckRunnable  ble"  );
                try {
                    Thread.sleep(500);
                    if (blueadapter != null) {
                        if (!blueadapter.isEnabled()) {
                            blueadapter.enable();
                            Thread.sleep(5000);
                            mBleMan.initialize();
                            mBleMan.scanLeDevice(false);
                            mBleMan.scanLeDevice(true);
                            mBleMan.cleanAll();
                        }
                    }
                    //deviceList.get(j).getMac().equals(info.getMac())
                    getScanCnt++;
                    if (getScanCnt > 10) {
                        if (mBleMan.GetScanCallback() == 0) {
                            mBleMan.scanLeDevice(true);
                            //Log.e(TAG, "devCtlFbCheckRunnable  sble"  );
                        }
                    }

                    deviceStatusCheck();

                } catch (Exception e) {
                    //Log.e(TAG, "write  data IOException" + e);
                }
            }
        }
    };

    public void addToDevList() {

        DbManager db = CommonUtil.MyDbUtils();
        try {

//            List<DeviceDb> listBleDb = db.findAll(DeviceDb.class);
            List<DeviceDb> listBleDb = db.selector(DeviceDb.class).findAll();
            if (listBleDb == null) {
                logPrint(TAG, "Not Device add to list!");
                return;
            }

            for (int i = 0; i < mDevInfoItem.size(); i++) {
                if (mDevInfoItem.get(i).getBtGatt() != null) {
                    mDevInfoItem.get(i).getBtGatt().disconnect();
                    mDevInfoItem.get(i).setBtGatt(null);
                }
            }
            mDevInfoItem.clear();

            for (final DeviceDb item : listBleDb) {
                if (item.getNetType() == BLE_NETWORK) {
                    DevInfoItem mDev = new DevInfoItem(item.getDevId(), item.getType(), item.getMacAddr(), null);
                    mDevInfoItem.add(mDev);
                    item.setStatus(0);
                    db.saveOrUpdate(item);
                }
                //mListTopBoxMac.add(item.getDevMAC());        
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    public boolean addNewDev(int deviceType, String boxId, String devId, String mac, String name) {
        DbManager db = CommonUtil.MyDbUtils();
        try {

            DeviceDb ZBData = new DeviceDb(boxId, devId, name, DeviceList.BLE_NETWORK, deviceType, mac, -1);
            DeviceDb me = db.selector(DeviceDb.class).where("devId", "=", devId).findFirst();
            if (me == null) {
                db.save(ZBData);
            } else {
                Log.e(TAG, "This device registered,devID:" + devId);
                intentRsp(ACTION_BLE_ADD, 1);
                return false;
            }
        } catch (DbException | NumberFormatException e) {
            e.printStackTrace();
            return false;
        }

        intentRsp(ACTION_BLE_ADD, 0);
        if (deviceType != TYPE_DOOR_SENSOR) {
            DevInfoItem mDev = new DevInfoItem(devId, deviceType, mac, null);
            mDevInfoItem.add(mDev);
        }
        return true;
    }

    public boolean deleteDev(String devId) {
        return false;
    }

    void airStationProc(DeviceDb me, String mac, byte[] datas) {
        byte[] devSerialNo = CommonUtil.getSpecbyte(datas, BLE_ADV_DEV_ID_ADDR, 12);
        devSerialNo = CommonUtil.exchangebyte(devSerialNo);
        String advdatas = new String(devSerialNo);

        int temp = (datas[BLE_ADV_TEMP_DATA_ADDR]) & 0xff;
        temp = (temp | ((datas[BLE_ADV_TEMP_DATA_ADDR + 1] << 8) & 0xff00));

        int humi = (datas[BLE_ADV_HUMI_DATA_ADDR]) & 0xff;
        humi = (humi | ((datas[BLE_ADV_HUMI_DATA_ADDR + 1] << 8) & 0xff00));

        int pm25 = (datas[BLE_ADV_PM25_DATA_ADDR]) & 0xff;
        pm25 = (pm25 | ((datas[BLE_ADV_PM25_DATA_ADDR + 1] << 8) & 0xff00));

        int co2 = (datas[BLE_ADV_CO2_DATA_ADDR]) & 0xff;
        co2 = (co2 | ((datas[BLE_ADV_CO2_DATA_ADDR + 1] << 8) & 0xff00));

        int msg = (datas[BLE_ADV_MSG_DATA_ADDR]) & 0xff;

        Log.d(TAG, "Mac: " + mac + "|" + "devId :" + advdatas + "temp: " + (temp / 10) + "humi: " + (humi / 10) + "pm25: " + (pm25) + "co2: " + (co2) + "msg: " + (msg));

        try {
            if (me != null) {
                me.setTEMP(temp / 10);
                me.setHumidity(humi / 10);
                me.setPM25(pm25);
                me.setCO2(co2);
                me.setAsMag(msg);
                mBleDb.saveOrUpdate(me);
                //发送状态改变广播到上层
                CommonUtil.sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,me.getBoxId(),me.getDevId(),me.getType(),false,null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void doorSensorProc(DeviceDb me, String mac, byte[] datas) {
        int msg = (datas[BLE_ADV_MSG_DATA_ADDR]) & 0xff;

        try {
            if (me != null && me.getAsMag() != msg) {
                me.setAsMag(msg);
                mBleDb.saveOrUpdate(me);
                if (msg == 0)
                    Log.e(TAG, "door Close!!!!! ");
                else
                    Log.e(TAG, "door Open!!!!!!!!!! ");

                //发送状态改变广播到上层
                CommonUtil.sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,me.getBoxId(),me.getDevId(),me.getType(),false,null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void shockSensorProc(DeviceDb me, String mac, byte[] datas) {
        int msg = (datas[BLE_ADV_MSG_DATA_ADDR]) & 0xff;

        try {
            if (me != null && me.getAsMag() != msg) {
                me.setAsMag(msg);
                mBleDb.saveOrUpdate(me);
                Log.e(TAG, "shock msg update Db");
                //发送状态改变广播到上层
                CommonUtil.sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,me.getBoxId(),me.getDevId(),me.getType(),false,null);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private int airRadioCnt = 0;

    DbManager mBleDb = null;

    private int findDevice(String devid) {
        int size = mDevInfoItem.size();
        for (int j = 0; j < size; j++) {
            if (mDevInfoItem.get(j).getDevId().equals(devid)) {
                return j;
            }
        }
        return (size + 10);
    }

    private void deviceStatus(String devid, int status) {
        int index = 0;
        index = findDevice(devid);
        if (mDevInfoItem.size() > index) {
            if (status == DeviceManager.Dev_STATUS_eConnected) {
                mDevInfoItem.get(index).setCnt(0);
            }
            mDevInfoItem.get(index).setState(status);
        }
    }

    private void deviceStatusCheck() {
        int size = mDevInfoItem.size();
        int temp;
        //Log.e(TAG, "deviceStatusCheck  enter size:" + size);
        for (int j = 0; j < size; j++) {
            temp = mDevInfoItem.get(j).getCnt();
            if (mDevInfoItem.get(j).getDevType() == TYPE_TOPBOX || mDevInfoItem.get(j).getDevType() == TYPE_AIR_RADIO) {
                return;
            }
            if (temp == 60) {
                setStatus2Db(mDevInfoItem.get(j).getDevId(), DeviceManager.Dev_STATUS_eDisconnect);
            }
            mDevInfoItem.get(j).setCnt(temp + 1);

        }
    }

    private void setStatus2Db(String devid, int status) {
        DbManager db = CommonUtil.MyDbUtils();
        mBleDb = db;
        try {
            DeviceDb me = db.selector(DeviceDb.class).where("devId", "=", devid).findFirst();
            if (me != null) {
                deviceStatus(me.getDevId(), status);
                me.setStatus(status);
                mBleDb.saveOrUpdate(me);
            }

        } catch (DbException | NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void setStatus2Db(DeviceDb me, int status) {
        try {
            if (me != null) {
                deviceStatus(me.getDevId(), status);
                me.setStatus(status);
                mBleDb.saveOrUpdate(me);
            }
        } catch (DbException | NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void updateMagDb(String mac, byte[] datas) {
        DbManager db = CommonUtil.MyDbUtils();
        mBleDb = db;
        try {
            DeviceDb me = db.selector(DeviceDb.class).where("macAddr", "=", mac).findFirst();
            int type;
            if (me != null) {
                type = me.getType();

                setStatus2Db(me, DeviceManager.Dev_STATUS_eConnected);
                if (type == TYPE_DOOR_SENSOR) {
                    doorSensorProc(me, mac, datas);
                } else if (type == TYPE_AIR_RADIO) {
                    airRadioCnt++;
                    if (airRadioCnt >= 20) {   // 目前为 5  暂时改20看看
                        airStationProc(me, mac, datas);
                        byte[] devSerialNo = CommonUtil.getSpecbyte(datas, BLE_ADV_DEV_ID_ADDR, 12);
                        airRadioCnt = 0;
                    }
                    Log.d(TAG, "Mac: " + mac + "|" + "updateMagDb: " + airRadioCnt);
                } else if (type == TYPE_SHOCK_SENSOR) {
                    shockSensorProc(me, mac, datas);
                }
                db.saveOrUpdate(me);
            }
        } catch (DbException | NumberFormatException e) {
            e.printStackTrace();
        }
    }

    public boolean aceessConn(String mac) {
        long timestamp = System.currentTimeMillis();
        boolean dev = false;
        for (int i = 0; i < mDevInfoItem.size(); i++) {
            if (mac.equals(mDevInfoItem.get(i).getDevMAC())) {
                Log.e(TAG, "aceessConn:" + "time" + timestamp + "time" + mDevInfoItem.get(i).getTimestamp());
                if (timestamp - mDevInfoItem.get(i).getTimestamp() > 5000) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        return dev;
    }

    private void bleDevsConnect(String mac) {
        String devMac = mac.replace(":", "");
        DbManager db = CommonUtil.MyDbUtils();
        mBleDb = db;
        try {
            DeviceDb me = db.selector(DeviceDb.class).where("macAddr", "=", devMac).findFirst();

            if (me != null) {
                if (me.getType() == TYPE_TOPBOX || me.getType() == TYPE_AIR_RADIO) {
                    if (!aceessConn(devMac)) {
                        Log.e(TAG, "ble delay Connect +mac" + devMac);
                        return;
                    }
                    if (mBleMan.connect(mac)) {
                        setStatus2Db(me, DeviceManager.Dev_STATUS_eConnected);
                        Log.e(TAG, "ble Trying Connect +mac" + mac);
                    }

                }
            }
        } catch (DbException | NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            Log.e(TAG, "BLE_receive :" + action);
            if (intent.getAction().equals(ACTION_BLE_ADD)) {
                Log.e(TAG, "ACTION_BLE_ADD");

                try {
                    String boxId = intent.getStringExtra("boxId");
                    int devType = intent.getIntExtra("type", 0);
                    int network = intent.getIntExtra("network", 0);
                    String devId = intent.getStringExtra("deviceId");
                    String mac = intent.getStringExtra("macAddr").toUpperCase();
                    String name = intent.getStringExtra("name");

                    if (mac.length() > 0 && network == BLE_NETWORK) {
                        if (devType == TYPE_DOOR_SENSOR) {
                            if ((!mListMacAndState.contains(mac + "-1")) && (!mListMacAndState.contains(mac + "+0")) && (!mListMacAndState.contains(mac + "+1"))) {
                                if (addNewDev(devType, boxId, devId, mac, name)) {
                                    mac = mac + "-1";
                                    mListMacAndState.add(mac);
                                    Log.e(TAG, "ACTION_BLE_ADD:" + mac);
                                    Log.e(TAG, "Dev List:" + mListMacAndState.toString());
                                }
                            }
                        } else {
                            int auto_flag = 1;
                            if (auto_flag != 0) {
                                DbManager db = CommonUtil.MyDbUtils();
                                try {
                                    List<Navigation> NavigationDb = db.findAll(Navigation.class);
                                    if (NavigationDb == null) {

                                    } else {
                                        for (final Navigation item : NavigationDb) {
                                            if (item.getDevId().equals(devId)) {
                                                item.setType(devType);
                                                db.saveOrUpdate(item);
                                                auto_flag = 0;
                                                break;
                                            }
                                        }

                                    }

                                    if (auto_flag != 0) {
                                        NavigationDao dao3 = new NavigationDao(mContext);
                                        Navigation nav = new Navigation();
                                        nav.setDevId(devId);
                                        nav.setType(devType);
                                        dao3.add(nav);
                                        Log.d(TAG, "ACTION_DEV_ADD,WiredNet NavigationDao");
                                    }

                                } catch (DbException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }

                            }
                            if (addNewDev(devType, boxId, devId, mac, name)) {
                                Log.e(TAG, "ACTION_BLE_ADD:" + mac);
                            }
                        }
                    } else if (mac.length() > 0 && network == WIFI_NETWORK) {
                        if (devType == TYPE_MASTERBOX) {
                            if (addNewDev(devType, boxId, devId, mac, name)) {
                                Log.e(TAG, "ACTION_BLE_ADD Master Box:" + mac);
                            }
                        }
                    }


                } catch (Exception e) {
                    Log.e(TAG, "Error:" + e);
                }

            } else if (intent.getAction().equals(ACTION_BLE_DELETE)) {
                int network = intent.getIntExtra("network", 0);
                String devId = intent.getStringExtra("deviceId");
                String mac = intent.getStringExtra("macAddr");
                if (network == BleService.BLE_NETWORK) {
                    if (deleteDev(devId)) {
                        mListMacAndState.remove(mListMacAndState.remove(mac + "+0"));
                        mListMacAndState.remove(mListMacAndState.remove(mac + "+1"));
                        mListMacAndState.remove(mListMacAndState.remove(mac + "-1"));

                        intentRsp(ACTION_BLE_DELETE, 0);
                    } else {
                        intentRsp(ACTION_BLE_DELETE, 1);
                    }
                }

                logPrint(TAG, "ACTION_BLE_DELETE devId:" + devId + ",MAC:" + mac);
            } else if (intent.getAction().equals(ACTION_HCP_UPDATED)) {
                logPrint(TAG, "ACTION_HCP_UPDATED ");
                addToDevList();
            } else if (ACTION_DEV_CTL_BY_BLE.equals(intent.getAction())) {
                String currentAction = intent.getStringExtra("currentAction");
                intent.setAction(currentAction);
                intentControlCmdProc(intent);
            }
        }

    };

    private void intentControlCmdProc(Intent intent) {
        if (intent.getAction().equals(ACTION_CTL_LIGHT)) {

            if (debug) Log.d(TAG, "ACTION_CTL_LIGHT");
            try {
                String deviceId = intent.getStringExtra("deviceId");
                String mac = intent.getStringExtra("macAddr");

                int sw = 0;
                int brgn = 0;
                int color = 0;

                int network = 0;

                DbManager db = CommonUtil.MyDbUtils();
                try {
                    DeviceDb me = db.selector(DeviceDb.class).where("devId", "=", deviceId).findFirst();
                    if (me != null) {
                        mac = me.getMacAddr();
                        network = me.getNetType();
                        sw = intent.getIntExtra("sw", me.getSw());
                        brgn = intent.getIntExtra("brightness", me.getBrightness());
                        color = intent.getIntExtra("color", me.getColor());
                    }
                } catch (DbException | NumberFormatException e) {
                    e.printStackTrace();
                }

                if (network == BLE_NETWORK) {
                    if (debug)
                        Log.d(TAG, "MAC:" + mac + ",sw:" + sw + ",brightness:" + brgn + ",color:" + color);

                    if (mac.length() > 0) {
                        intentRsp(ACTION_CTL_LIGHT, 0);
                        if (color != -1) {
                            mHandler.removeMessages(YEELIGHT_COLOR_BRIGHTNESS);

                            Message msg = Message.obtain();
                            msg.what = YEELIGHT_COLOR_BRIGHTNESS;
                            msg.obj = mac;
                            msg.arg1 = color;
                            msg.arg2 = brgn;
                            mHandler.sendMessageDelayed(msg, YEELIGHT_CTL_MDELAY);
                        } else {
                            mHandler.removeMessages(YEELIGHT_BRIGHTNESS);
                            Message msg = Message.obtain();
                            msg.what = YEELIGHT_BRIGHTNESS;
                            msg.obj = mac;
                            msg.arg1 = brgn;
                            mHandler.sendMessageDelayed(msg, YEELIGHT_CTL_MDELAY);
                        }
                    } else {
                        intentRsp(ACTION_CTL_LIGHT, 1);
                        Log.e(TAG, "Light net address is invalid!");
                    }
                }
            } catch (Exception e) {
                intentRsp(ACTION_CTL_LIGHT, 1);
                Log.e(TAG, "Error:" + e);
            }
        } else if (intent.getAction().equals(ACTION_CTL_AIRCONDITION)) {

            if (debug) Log.d(TAG, "ACTION_CTL_AIRCONDITION");
            try {
                String deviceId = intent.getStringExtra("deviceId");
                String mac = intent.getStringExtra("macAddr");
                int netType = intent.getIntExtra("network", -1);

                if (netType == -1) {
                    //return ;
                }

                int sw = 0;
                int mode = intent.getIntExtra("mode", 0x0);
                int temp = 25;
                int wind = 0;
                int wipe = 0;

                DbManager db = CommonUtil.MyDbUtils();
                try {
                    DeviceDb me = db.selector(DeviceDb.class).where("devId", "=", deviceId).findFirst();
                    if (me != null) {
                        mac = me.getMacAddr();
                        netType = me.getNetType();


                        sw = intent.getIntExtra("sw", me.getSw());
                        temp = intent.getIntExtra("temperature", me.getSetTemp());
                        wind = intent.getIntExtra("wind", me.getWind());
                        wipe = intent.getIntExtra("wipe", me.getWipe());
                        mode = intent.getIntExtra("mode", me.getMode());
                        if (mode == 0)
                            mode = 5;
                        Log.i(TAG, "sw:" + sw + "temp:" + temp + ",wind:" + wind + ",mode:" + mode + ",netWork:" + netType);

                    } else {
                        Log.d(TAG, "Air-Condittion: Not found, devId:" + deviceId);
                    }

                } catch (DbException | NumberFormatException e) {
                    e.printStackTrace();
                }

                if (netType == BLE_NETWORK) {
                    mTopBox.airConditionCtl(mac, TopBoxDev.TYPE_Other_DEVICE, sw, mode, temp, wind, wipe, 0);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error:" + e);
            }
        } else if (intent.getAction().equals(ACTION_CTL_AIRCLEANER)) {
            if (debug) Log.d(TAG, "ACTION_CTL_AIRCLEANER");

            Log.e(TAG, "ACTION_CTL_AIRCLEANER");
            try {
                String deviceId = intent.getStringExtra("deviceId");
                String mac = intent.getStringExtra("macAddr");
                boolean sw = intent.getBooleanExtra("sw", false);
                boolean mode = intent.getBooleanExtra("mode", false);
                boolean wind = intent.getBooleanExtra("wind", false);
                boolean timer = intent.getBooleanExtra("timer", false);

                DbManager db = CommonUtil.MyDbUtils();
                try {
                    DeviceDb me = db.selector(DeviceDb.class).where("devId", "=", deviceId).findFirst();
                    if (me != null) {
                        mac = me.getMacAddr();
                        mTopBox.AirCleanerCtl(mac, TopBoxDev.TYPE_AIRCLEANER_DEVICE, sw, mode, wind, timer);
                    } else {
                        Log.e(TAG, "AirCleaner: Not found, devId:" + deviceId);
                    }

                } catch (DbException | NumberFormatException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                Log.e(TAG, "Error:" + e);
            }
        }else if (intent.getAction().equals(ACTION_CTL_PROJECTOR)) {
            if (debug) Log.d(TAG, "ACTION_CTL_PROJECTOR");
            Log.d(TAG, "ACTION_CTL_PROJECTOR");
            try {
                String deviceId = intent.getStringExtra("deviceId");
                String mac = intent.getStringExtra("macAddr");

                int sw;
                DbManager db = CommonUtil.MyDbUtils();
                try {
                    DeviceDb me = db.selector(DeviceDb.class).where("devId", "=", deviceId).findFirst();
                    sw = intent.getIntExtra("sw", me.getSw());

                    if (me != null) {
                        mac = me.getMacAddr();
                        mTopBox.projectorCtl(mac, TopBoxDev.TYPE_Other_DEVICE,sw);
                    } else {
                        Log.d(TAG, "PROJECTOR: Not found, devId:" + deviceId);
                    }
                } catch (DbException | NumberFormatException e) {
                    e.printStackTrace();

                }



            } catch (Exception e) {
                Log.d(TAG, "Error:" + e);
            }
        }
    }

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == YEELIGHT_BRIGHTNESS && msg.obj != null) {
                mYeeLight.setYeeBright((String) msg.obj, msg.arg1);
            } else if (msg.what == YEELIGHT_COLOR_BRIGHTNESS && msg.obj != null) {
                mYeeLight.setYeeColorBright((String) msg.obj, msg.arg1, msg.arg2);
            }
        }
    };

    public void intentRsp(String intent, int result) {
        Intent mIntent = new Intent(ACTION_INFO_RETURN);
        mIntent.putExtra("intentId", intent);
        mIntent.putExtra("return", result);
        mContext.sendBroadcast(mIntent);
    }

    public class LocalBinder extends Binder {
        BleService getService() {
            return BleService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // After using a given device, you should make sure that BluetoothGatt.close() is called
        // such that resources are cleaned up properly.  In this particular example, close() is
        // invoked when the UI is disconnected from the Service.
        //close();
        return super.onUnbind(intent);
    }

    private final IBinder mBinder = new LocalBinder();

    @Override
    public void onDestroy() {
        super.onDestroy();

        for (int i = 0; i < mDevInfoItem.size(); i++) {
            if (mDevInfoItem.get(i).getBtGatt() != null) {
                mDevInfoItem.get(i).getBtGatt().disconnect();
                mDevInfoItem.get(i).setBtGatt(null);
            }
            Log.e(TAG, "onDestroy...");
        }
        CommonUtil.MyDbUtilsClose();
        mContext.unregisterReceiver(mReceiver);
    }
}
